package com.study.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.exception.BusinessException;
import com.study.exception.ErrorCode;
import com.study.exception.ThrowUtils;
import com.study.model.dto.favoritePost.FavoritePostQueryRequest;
import com.study.model.dto.post.PostAddRequest;
import com.study.model.dto.post.PostQueryRequest;
import com.study.model.dto.post.PostUpdateRequest;
import com.study.model.dto.topic.TopicQueryRequest;
import com.study.model.entity.FavoritePost;
import com.study.model.entity.Post;
import com.study.model.entity.Topic;
import com.study.model.vo.FavoritePostVO;
import com.study.model.vo.PostVO;
import com.study.model.vo.TopicVO;
import com.study.model.vo.UserVO;
import com.study.service.FavoritePostService;
import com.study.service.PostService;
import com.study.mapper.PostMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @description 针对表【post(帖子)】的数据库操作Service实现
*/
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post>
    implements PostService {
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    @Lazy
    private FavoritePostService favoritePostService;

    /**
     * 创建帖子
     *
     * @param postAddRequest
     * @param request
     * @return
     */
    @Override
    public Long createPost(PostAddRequest postAddRequest, HttpServletRequest request) {
        if (postAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (postAddRequest.getTitle() == null) {
            postAddRequest.setTitle("默认帖子标题");
        }
        Post post = new Post();
        BeanUtils.copyProperties(postAddRequest, post);
        post.setUserId(userService.getLoginUser(request).getId());
        boolean save = this.save(post);
        if (!save) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "创建失败");
        }
        return post.getId();    }

    /**
     * 根据id获取帖子
     *
     * @param id
     * @return
     */
    @Override
    public PostVO getPostVOById(long id) {
        Post post = this.baseMapper.selectById(id);
        ThrowUtils.throwIf(post == null, ErrorCode.NOT_FOUND_ERROR);
        PostVO postVO = new PostVO();
        BeanUtils.copyProperties(post, postVO);
        return postVO;    }

    /**
     * 更新帖子
     *
     * @param postUpdateRequest
     * @return
     */
    @Override
    public Boolean updatePost(PostUpdateRequest postUpdateRequest) {
        if (postUpdateRequest == null || postUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Post post = this.baseMapper.selectById(postUpdateRequest.getId());
        BeanUtils.copyProperties(postUpdateRequest, post);
        return this.updateById(post);
    }

    /**
     * 分页获取帖子列表（包括查询）
     *
     * @param postQueryRequest
     * @return
     */
    @Override
    public Page<PostVO> listPostVOByPage(PostQueryRequest postQueryRequest) {
        if (postQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize();
        Page<Post> postPage = page(new Page<>(current, size), getQueryWrapper(postQueryRequest));
        Page<PostVO> postVOPage= new Page<>(current, size, postPage.getTotal());
        List<PostVO> postVOList = getPostVoList(postPage.getRecords());
        for (PostVO postVO : postVOList) {
            UserVO userVO = userService.getUserVOById(postVO.getUserId());
            String userAccount = userVO.getUserAccount();
            String userName = userVO.getUserName();
            String userAvatar = userVO.getUserAvatar();
            String userRole = userVO.getUserRole();
            postVO.setUserAccount(userAccount);
            postVO.setUserName(userName);
            postVO.setUserAvatar(userAvatar);
            postVO.setUserRole(userRole);

        }
        postVOPage.setRecords(postVOList);
        return postVOPage;    }

    /**
     * 删除帖子
     *
     * @param id
     * @return
     */
    @Override
    public Boolean romovePost(Long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        FavoritePostQueryRequest favoritePostQueryRequest = new FavoritePostQueryRequest();
        favoritePostQueryRequest.setPostId(id);
        Page<FavoritePostVO> postVOPage = favoritePostService.listFavoritePostVOByPage(favoritePostQueryRequest);
        if (postVOPage.getTotal() > 0) {
            for (FavoritePostVO favoritePostVO : postVOPage.getRecords()) {
                Long favoritePostVOId = favoritePostVO.getId();
                favoritePostService.removeById(favoritePostVOId);
            }
        }
        if (this.removeById(id)) {
            return true;
        }
        return false;
    }

    /**
     * 获取帖子VO列表
     * @param records
     * @return
     */
    private List<PostVO> getPostVoList(List<Post> records) {
        if (CollUtil.isEmpty(records)) {
            return new ArrayList<>();
        }
        return records.stream().map(this::getPostVO).collect(Collectors.toList());
    }

    private PostVO getPostVO(Post post) {
        if (post == null) {
            return null;
        }
        PostVO postVO = new PostVO();
        BeanUtils.copyProperties(post, postVO);
        return postVO;
    }

    /**
     * 获取帖子分页QueryWrapper
     * @param postQueryRequest
     * @return
     */
    public QueryWrapper<Post> getQueryWrapper(PostQueryRequest postQueryRequest) {
        if (postQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = postQueryRequest.getId();
        Long userId = postQueryRequest.getUserId();
        Long topicId = postQueryRequest.getTopicId();
        String title = postQueryRequest.getTitle();
        String content = postQueryRequest.getContent();
        Date createTime = postQueryRequest.getCreateTime();

        String sortField = postQueryRequest.getSortField();
        String sortOrder = postQueryRequest.getSortOrder();



        QueryWrapper<Post> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotNull(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotNull(topicId), "topicId", topicId);
        queryWrapper.like(StrUtil.isNotBlank(title), "title", title);
        queryWrapper.like(StrUtil.isNotBlank(content), "content", content);
        queryWrapper.like(StrUtil.isNotBlank((CharSequence) createTime), "createTime", createTime);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }
}




